#include "tensor_mat_multi_cav.h"
#include <fstream>
#include <sstream>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <ctime>

namespace TensorMatMultiCavity {

// Global MPI variables
int mpi_rank = 0;
int mpi_size = 1;
int mpi_procs_x = 1;
int mpi_procs_y = 1;
int mpi_coords[2] = {0, 0};
int debug_level = DEBUG_WARNING;

// Constructor
MultiCavityTensorMatrix::MultiCavityTensorMatrix(int imt, int jmt, int kmt) 
    : imt(imt), jmt(jmt), kmt(kmt) {
    data = new float[imt * jmt * kmt];
    std::fill(data, data + imt * jmt * kmt, 0.0f);
}

// Destructor
MultiCavityTensorMatrix::~MultiCavityTensorMatrix() {
    delete[] data;
}

// Access element
float& MultiCavityTensorMatrix::operator()(int i, int j, int k) {
    return data[k * (imt * jmt) + j * imt + i];
}

float MultiCavityTensorMatrix::operator()(int i, int j, int k) const {
    return data[k * (imt * jmt) + j * imt + i];
}

// Initialize with test pattern
void MultiCavityTensorMatrix::initialize_test_pattern() {
    for (int k = 0; k < kmt; k++) {
        for (int j = 0; j < jmt; j++) {
            for (int i = 0; i < imt; i++) {
                data[k * (imt * jmt) + j * imt + i] = i + j + k;
            }
        }
    }
}

// Initialize with random values
void MultiCavityTensorMatrix::initialize_random() {
    std::srand(std::time(nullptr));
    for (int k = 0; k < kmt; k++) {
        for (int j = 0; j < jmt; j++) {
            for (int i = 0; i < imt; i++) {
                data[k * (imt * jmt) + j * imt + i] = static_cast<float>(std::rand()) / RAND_MAX;
            }
        }
    }
}

// Matrix-vector multiplication
void MultiCavityTensorMatrix::mat_vec_mult(const float* vec, float* result) const {
    for (int k = 0; k < kmt; k++) {
        for (int j = 0; j < jmt; j++) {
            for (int i = 0; i < imt; i++) {
                float sum = 0.0f;
                for (int kk = -1; kk <= 1; kk++) {
                    for (int jj = -1; jj <= 1; jj++) {
                        for (int ii = -1; ii <= 1; ii++) {
                            int ni = i + ii;
                            int nj = j + jj;
                            int nk = k + kk;
                            if (ni >= 0 && ni < imt && nj >= 0 && nj < jmt && nk >= 0 && nk < kmt) {
                                sum += data[nk * (imt * jmt) + nj * imt + ni] * vec[nk * (imt * jmt) + nj * imt + ni];
                            }
                        }
                    }
                }
                result[k * (imt * jmt) + j * imt + i] = sum;
            }
        }
    }
}

// Convert to CSR format
void MultiCavityTensorMatrix::convert_to_csr(std::vector<float>& values, 
                                           std::vector<int>& column_indices,
                                           std::vector<int>& row_pointers) const {
    values.clear();
    column_indices.clear();
    row_pointers.clear();
    
    row_pointers.push_back(0);
    int nnz = 0;
    
    for (int k = 0; k < kmt; k++) {
        for (int j = 0; j < jmt; j++) {
            for (int i = 0; i < imt; i++) {
                for (int kk = -1; kk <= 1; kk++) {
                    for (int jj = -1; jj <= 1; jj++) {
                        for (int ii = -1; ii <= 1; ii++) {
                            int ni = i + ii;
                            int nj = j + jj;
                            int nk = k + kk;
                            if (ni >= 0 && ni < imt && nj >= 0 && nj < jmt && nk >= 0 && nk < kmt) {
                                values.push_back(data[nk * (imt * jmt) + nj * imt + ni]);
                                column_indices.push_back(nk * (imt * jmt) + nj * imt + ni);
                                nnz++;
                            }
                        }
                    }
                }
                row_pointers.push_back(nnz);
            }
        }
    }
}

// Print matrix info
void MultiCavityTensorMatrix::print_info() const {
    std::cout << "Matrix dimensions: " << imt << "x" << jmt << "x" << kmt << std::endl;
    std::cout << "Total elements: " << imt * jmt * kmt << std::endl;
}

// Debug: verify connections
void MultiCavityTensorMatrix::verify_connections() const {
    for (int k = 0; k < kmt; k++) {
        for (int j = 0; j < jmt; j++) {
            for (int i = 0; i < imt; i++) {
                float val = data[k * (imt * jmt) + j * imt + i];
                if (val != 0.0f) {
                    std::cout << "Non-zero element at (" << i << "," << j << "," << k 
                              << "): " << val << std::endl;
                }
            }
        }
    }
}

// Debug: communicate boundaries
void MultiCavityTensorMatrix::communicate_boundaries() {
    // This is a placeholder for boundary communication
    // The actual implementation will be in the grid decomposition code
}

} // namespace TensorMatMultiCavity